package com.probiz.estore.product.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.probiz.estore.common.model.product.ProductMedia;
import com.probiz.estore.core.dao.impl.HibernateGenericDaoImpl;
import com.probiz.estore.product.dao.ProductMediaDao;

/**
 * Dao implementation for ProductMedia.
*/
public class ProductMediaDaoImpl extends HibernateGenericDaoImpl<ProductMedia> implements ProductMediaDao {

	@SuppressWarnings("unchecked")
	public List<ProductMedia> findProductMediaByProductIdAndType(
			Integer productId, Short...mediaType) {
//		String hql="from ProductMedia pm where pm.product.productId=? and pm.mediaType=? order by pm.sortOrder asc";
		StringBuffer hql=new StringBuffer("from ProductMedia pm where pm.product.productId=? ");
		List<Object> objList=new ArrayList<Object>();
		objList.add(productId);
		if(mediaType.length>1){
			hql.append("and pm.mediaType in(");
			for (int i = 0; i < mediaType.length; i++) {
				if(i!=0)
					hql.append(",");
				hql.append("?");
				objList.add(mediaType[i]);
			}
			hql.append(")");
		}else{
			hql.append("and pm.mediaType=?");
			objList.add(mediaType[0]);
		}
		hql.append(" order by pm.sortOrder asc");
		List<ProductMedia> productMedias=findByHql(hql.toString(), objList.toArray());
		return productMedias;
	}
	
	public List<ProductMedia> getProductMediaByMediaUrl(final String url) {
		List list;
		list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				StringBuffer sb = new StringBuffer();
				sb.append("from ProductMedia where mediaUrl like '%"+url+"%'");
				Query query = session.createQuery(sb.toString());
				List rows = query.list();
				return rows;
			}
		});
		return list;
	}

}
